<!--
Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

https://www.mall4j.com/

未经允许，不可做商业用途！

版权所有，侵权必究！
-->

<template>
  <!-- 基本设置 -->
  <view class="Mall4j page-store-settings-basic">
    <uni-forms
      ref="baseInfoFormRef"
      :model-value="baseInfoForm"
      :rules="rules"
      validate-trigger="submit"
    >
      <view class="setting-info-item">
        <uni-forms-item name="merchantName">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              商家名称
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="baseInfoForm.merchantName"
              placeholder="请输入商家名称"
              maxlength="10"
              @blur="checkInput('merchantName')"
            />
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item">
        <uni-forms-item name="shopName">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              店铺名称
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="baseInfoForm.shopName"
              placeholder="请输入店铺名称"
              maxlength="20"
              @blur="checkInput('shopName')"
            />
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item">
        <uni-forms-item name="tel">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              联系方式
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="baseInfoForm.tel"
              placeholder="请输入联系方式"
              maxlength="11"
              @blur="checkInput('tel')"
            />
          </view>
        </uni-forms-item>
      </view>
      <!-- 店铺简介 -->
      <view class="setting-info-item">
        <uni-forms-item name="intro">
          <view class="title">
            <text class="txt">
              店铺简介
            </text>
          </view>
          <view class="textarea-box">
            <textarea
              v-model="baseInfoForm.intro"
              placeholder="请输入店铺简介"
              maxlength="200"
              @blur="checkInput('intro')"
            />
          </view>
        </uni-forms-item>
      </view>
      <!-- 店铺logo -->
      <view class="setting-info-item">
        <uni-forms-item name="shopLogo">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              店铺logo
            </text>
          </view>
          <view class="upload-image">
            <view class="upload-con">
              <view
                v-if="!baseInfoForm.shopLogo"
                class="upload-btn"
                @tap="uploadImg('shopLogo')"
              >
                <view class="up-text text-btn">
                  +添加
                </view>
                <view class="up-text">
                  上传清晰照片
                </view>
              </view>
              <view
                v-if="baseInfoForm.shopLogo"
                class="upload-con"
                @tap.stop="previewImg(baseInfoForm.shopLogo)"
              >
                <image
                  :src="util.checkFileUrl(baseInfoForm.shopLogo)"
                  mode="aspectFit"
                  class="up-img-con"
                />
                <view
                  class="del-btn"
                  @click.stop="delLoadImg('shopLogo')"
                />
              </view>
            </view>
          </view>
        </uni-forms-item>
      </view>

      <view
        v-if="util.isAuthorities('shop:shopDetail:save') && (baseInfoForm.shopStatus !== 5)"
        class="footer"
      >
        <button
          type="default"
          class="button"
          hover-class="none"
          @tap="submit"
        >
          保存
        </button>
      </view>
    </uni-forms>
  </view>
</template>

<!-- eslint-disable n/no-callback-literal -->
<script setup>
import { reactive } from 'vue'
import util from '@/utils/util'

const Data = reactive({
  // 基本信息
  baseInfoForm: {
    merchantName: '',
    shopName: '',
    // contactName: '',
    tel: '',
    email: '',
    province: '',
    provinceId: '',
    city: '',
    cityId: '',
    area: '',
    areaId: '',
    currentAddr: '',
    shopAddress: '',
    shopLogo: '',
    intro: '',
    // 纬度
    shopLat: '',
    // 经度
    shopLng: ''
    // identityCardFront: '',
    // identityCardLater: '',
    // businessLicense: ''
  },
  rules: {
    // 对表单字段进行必填验证
    merchantName: {
      rules: [
        { required: true, errorMessage: '请输入商家名称' },
        { minLength: 2, maxLength: 10, errorMessage: '商家名称长度在2-10个字符之间' }
      ]
    },
    shopName: {
      rules: [
        { required: true, errorMessage: '请输入店铺名称' },
        { minLength: 2, maxLength: 20, errorMessage: '请输入2-20字以内的店铺名称' }
      ]
    },
    tel: {
      rules: [
        { required: true, errorMessage: '请输入联系方式' },
        {
          validateFunction: (rule, value, data, callback) => {
            const reg = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
            if (!reg.test(value)) {
              callback('请输入正确的联系方式')
              return false
            }
          }
        }
      ]
    },
    shopLogo: {
      rules: [
        { required: true, errorMessage: '请上传店铺logo' },
        {
          validateFunction: (rule, value, data, callback) => {
            // console.log(Data.baseInfoForm.shopLogo.trim())
            if (Data.baseInfoForm.shopLogo.trim().length === 0) {
              callback('请上传店铺logo')
              return false
            }
          }
        }
      ]
    }
  },
  areaList: [], // 全部地区

  addressShow: false
})

const { baseInfoForm, rules } = toRefs(Data)

const baseInfoFormRef = ref()

onLoad(() => {
  getShopDetailnfo()
  getAreaList()
})

onShow(() => {
  if (uni.getStorageSync('bbcLocInfo')) {
    const loc = uni.getStorageSync('bbcLocInfo')
    const shopAddress = setAddress(loc.poiaddress)
    Data.baseInfoForm.shopAddress = shopAddress
    Data.baseInfoForm.shopLat = loc.latlng.lat
    Data.baseInfoForm.shopLng = loc.latlng.lng
    uni.removeStorageSync('bbcLocInfo')
  }
})

onReady(() => {
  // 需要在onReady中设置规则
  baseInfoFormRef.value.setRules(Data.rules)
})

// 获取全部地区数据
const getAreaList = () => {
  http.request({
    url: '/admin/area/listAreaOfEnable',
    method: 'GET'
  }).then(({ data }) => {
    Data.areaList = data
  })
}
/**
* 上传图片
* @param {String} type
*/
// eslint-disable-next-line max-lines-per-function
const uploadImg = (type) => {
  // #ifdef APP-PLUS
  uni.chooseImage({
    count: 1, // 默认9
    sizeType: ['compressed'],
    sourceType: ['album'],
    success: (res) => {
      // 图片的本地临时文件路径列表
      const tempFilePaths = res.tempFilePaths[0]
      // 上传图片
      http.request({
        url: '/admin/file/getPreSignUrl',
        method: 'GET',
        data: { fileName: res.tempFiles[0].name, isImFile: false }
      }).then(({ data }) => {
        util.plusIo(tempFilePaths).then((buffer) => {
          uni.request({
            url: data.preSignUrl,
            method: 'PUT',
            data: buffer,
            success: function () {
              http.request({
                url: '/admin/file/uploadSuccess',
                method: 'PUT',
                data: [
                  {
                    fileId: data.fileId,
                    attachFileGroupId: 0,
                    type: 1,
                    fileSize: res.tempFiles[0].size
                  }
                ]
              }).then((responseData) => {
                if (responseData.code === '00000') {
                  // 根据上传传图片id 获取文件路径
                  http.request({
                    url: '/admin/file/attachFilePage',
                    method: 'get',
                    data: {
                      fileId: data.fileId,
                      current: 1,
                      size: 1,
                      type: 1
                    }
                  }).then(({ data }) => {
                    switch (type) {
                      case 'shopLogo':
                        // 店铺logo
                        Data.baseInfoForm.shopLogo = data.records[0].filePath
                        break
                      default:
                        break
                    }
                  })
                } else {
                  uni.showToast({
                    title: '上传失败',
                    icon: 'none'
                  })
                }
              })
            },
            fail: function () {
              uni.hideLoading()
            }
          })
        })
      })
    }
  })
  // #endif
  // #ifdef H5
  uni.chooseImage({
    count: 1, // 默认9
    sizeType: ['compressed'],
    sourceType: ['album'],
    success: (res) => {
      // 图片的本地临时文件路径列表
      const tempFilePaths = res.tempFilePaths[0]
      // 上传图片
      http.request({
        url: '/admin/file/getPreSignUrl',
        method: 'GET',
        data: { fileName: res.tempFiles[0].name, isImFile: false }
      }).then(({ data }) => {
        uni.request({
          url: tempFilePaths,
          method: 'GET',
          responseType: 'arraybuffer',
          success: function (requestRes) {
            uni.request({
              url: data.preSignUrl,
              method: 'PUT',
              data: requestRes.data,
              success: function () {
                http.request({
                  url: '/admin/file/uploadSuccess',
                  method: 'PUT',
                  data: [
                    {
                      fileId: data.fileId,
                      attachFileGroupId: 0,
                      type: 1,
                      fileSize: res.tempFiles[0].size
                    }
                  ]
                }).then((responseData) => {
                  if (responseData.code === '00000') {
                    // 根据上传传图片id 获取文件路径
                    http.request({
                      url: '/admin/file/attachFilePage',
                      method: 'get',
                      data: {
                        fileId: data.fileId,
                        current: 1,
                        size: 1,
                        type: 1
                      }
                    }).then(({ data }) => {
                      switch (type) {
                        case 'shopLogo':
                        // 店铺logo
                          Data.baseInfoForm.shopLogo = data.records[0].filePath
                          break
                        default:
                          break
                      }
                    })
                  } else {
                    uni.showToast({
                      title: '上传失败',
                      icon: 'none'
                    })
                  }
                })
              },
              fail: function () {
                uni.hideLoading()
              }
            })
          }
        })
      })
    }
  })
  // #endif
}

/**
* 删除图片
*
*/
const delLoadImg = (type) => {
  Data.baseInfoForm[type] = ''
}

// 详细地址反显
const setAddress = (address) => {
  if (!Data.areaList.length) return address

  let poiaddress = address.toString()
  const data = {
    province: '', // 省
    provinceId: '', // 省id
    city: '', // 市
    cityId: '', // 市id
    area: '', // 区
    areaId: '' // 区id
  }
  for (let i = 0; i < Data.areaList.length; i++) {
    if (poiaddress.indexOf(Data.areaList[i].areaName) === 0) {
      data.province = Data.areaList[i].areaName
      data.provinceId = Data.areaList[i].areaId
      poiaddress = poiaddress.replace(Data.areaList[i].areaName, '')
      for (let x = 0; x < Data.areaList[i].areas.length; x++) {
        let isGetCity = false
        if (poiaddress.indexOf(Data.areaList[i].areas[x].areaName) === 0) {
          data.city = Data.areaList[i].areas[x].areaName
          data.cityId = Data.areaList[i].areas[x].areaId
          poiaddress = poiaddress.replace(Data.areaList[i].areas[x].areaName, '')
          isGetCity = true
        }
        // 如果市级只有一个，直接选中
        if (Data.areaList[i].areas.length === 1) {
          data.city = Data.areaList[i].areas[x].areaName
          data.cityId = Data.areaList[i].areas[x].areaId
          poiaddress = poiaddress.replace(Data.areaList[i].areas[x].areaName, '')
          isGetCity = true
        }
        if (isGetCity) {
          for (let y = 0; y < Data.areaList[i].areas[x].areas.length; y++) {
            // eslint-disable-next-line max-depth
            if (poiaddress.indexOf(Data.areaList[i].areas[x].areas[y].areaName) === 0) {
              data.area = Data.areaList[i].areas[x].areas[y].areaName
              data.areaId = Data.areaList[i].areas[x].areas[y].areaId
              poiaddress = poiaddress.replace(Data.areaList[i].areas[x].areas[y].areaName, '')
              break
            }
          }
          break
        }
      }
      break
    }
  }
  if (data.provinceId && data.cityId && data.areaId) {
    Data.baseInfoForm.currentAddr = `${data.province} ${data.city} ${data.area}`
    Data.baseInfoForm = { ...Data.baseInfoForm, ...data }
    address = poiaddress
  }
  return address
}

/**
* 输入框空格校验
*/
const checkInput = (type) => {
  const reg = /^\s+$/g
  if (type === 'merchantName' && reg.test(Data.baseInfoForm.merchantName)) {
    Data.baseInfoForm.merchantName = ''
  }
  if (type === 'shopName' && reg.test(Data.baseInfoForm.shopName)) {
    Data.baseInfoForm.shopName = ''
  }
  if (type === 'tel' && reg.test(Data.baseInfoForm.tel)) {
    Data.baseInfoForm.tel = ''
  }
  if (type === 'email' && reg.test(Data.baseInfoForm.email)) {
    Data.baseInfoForm.email = ''
  }
  if (type === 'shopAddress' && reg.test(Data.baseInfoForm.shopAddress)) {
    Data.baseInfoForm.shopAddress = ''
  }
  if (type === 'intro' && reg.test(Data.baseInfoForm.intro)) {
    Data.baseInfoForm.intro = ''
  }
}

/**
* 提交表单
*/
const submit = () => {
  baseInfoFormRef.value.validate().then(() => {
    putShopDetail()
  })
}

/**
* 获取店铺信息
*/
const getShopDetailnfo = () => {
  http.request({
    url: '/shop/shopDetail/info',
    method: 'GET'
  }).then(({ data: res }) => {
    Data.baseInfoForm = res
    if (res.province && res.city && res.area) {
      Data.baseInfoForm.currentAddr = `${res.province} ${res.city} ${res.area}`
    }
  })
}

/**
* 修改店铺基本信息
*/
const putShopDetail = () => {
  const data = JSON.parse(JSON.stringify(Data.baseInfoForm))
  delete data.currentAddr
  http.request({
    url: '/shop/shopDetail',
    method: 'PUT',
    data
  }).then(() => {
    uni.showToast({
      title: '修改成功'
    })
  })
}

/**
*  图片预览
*/
const previewImg = (src) => {
  uni.previewImage({
    urls: [src]
  })
}
</script>

<style lang="scss" scoped>
@use "store-settings-basic";
</style>
